package com.roundarchisobar.njariwala.netflix.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.roundarchisobar.njariwala.netflix.dto.NetflixCatalogTitles;
import com.roundarchisobar.njariwala.netflix.dto.NetflixPeople;
import com.roundarchisobar.njariwala.netflix.request.SearchRequest;
import com.roundarchisobar.njariwala.netflix.service.NetflixSearchService;

@Controller
public class SearchController {

	private static final Logger logger = LoggerFactory.getLogger(SearchController.class);

	@Autowired
	private NetflixSearchService netflixSearchService;

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public String searchPageHandler(@Valid SearchRequest searchRequest, BindingResult result,
			HttpServletRequest request, Model model) {
		if (result.hasErrors()) {
			logger.error(result.getFieldErrors() + "");
		} else {

			String term = cleanSearchTerm(searchRequest.getTerm());
			searchRequest.setTerm(term);
			if (StringUtils.equals(searchRequest.getType(), "people")) {
				NetflixPeople netflixPeople = netflixSearchService.searchPeople(term);
				model.addAttribute("netflixPeople", netflixPeople);
			}
			if (StringUtils.equals(searchRequest.getType(), "title")) {
				NetflixCatalogTitles netflixCatalogTitles = netflixSearchService.searchTitle(searchRequest);

				model.addAttribute("startNum", (searchRequest.getPageNum() * searchRequest.getMaxResult()) + 1);
				long endNum = (searchRequest.getPageNum() + 1) * searchRequest.getMaxResult();
				if(netflixCatalogTitles.getNumberOfResults() < endNum){
					endNum = netflixCatalogTitles.getNumberOfResults();
				}
				model.addAttribute("endNum", endNum);

				model.addAttribute("netflixCatalogTitles", netflixCatalogTitles);
			}

		}
		model.addAttribute("searchRequest", searchRequest);
		model.addAttribute("searchTypes", netflixSearchService.getSearchTypeList());
		return "search";
	}

	private String cleanSearchTerm(String term) {
		term = term.replaceAll(" ", "");
		return term;
	}
}
